package com.eric.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @description： aop日志打印
 * @Author: liuBing
 * @DateTime: 2021/9/27 15:18
 */
@Aspect
@Component
@Slf4j
@Order(-1)
public class LogAop {


    /**
     * controller包作为切入点
     */
    @Pointcut("execution(public * com..*Controller.*(..)) || execution(public * com..*Web.*(..))")
    public void paramLog() {
    }


    /**
     * 请求信息日志打印
     *
     * @param joinPoint 切入点
     */
    @Before("paramLog()")
    public void validate(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            String method = request.getMethod();
            log.info("[httpLog] [{}]请求: {}", method, request.getRequestURL().toString());
            log.info("[httpLog] 请求方IP: {}", request.getRemoteAddr());

            String param;
            switch (method){
                case "GET":
                    param = request.getQueryString();
                    break;
                case "POST":
                default:
                    param =  getParam(joinPoint);
            }
            log.info("[httpLog] 请求param: {}", param);

//            Enumeration<String> enu = request.getParameterNames();
//            while (enu.hasMoreElements()) {
//                String paraName = enu.nextElement();
//                if (!StrUtil.isEmpty(request.getParameter(paraName))) {
//                    log.info("[httpLog] 问号后param: " + paraName + " : " + request.getParameter(paraName));
//                }
//            }

            // 参数日志打印后，空两行
            for (int i = 0; i < 2; i++) {
                log.info(" ");
            }
        } catch (Exception e) {
            log.error("aop -> 打印接收文件参数错误", e);
        }
    }


    public String getParam(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            // 排除 MultipartFile
            if (arg instanceof MultipartFile) {}
            else {
                return JSON.toJSONString(arg);
            }
        }
        return "参数为空";
    }
}
